<template>
  <div>
    <el-card>
      <el-row type="flex" justify="end">
        <el-button size="small" type="primary">添加角色</el-button>
      </el-row>
      <el-divider />
      <el-table border :data="roleList">
        <el-table-column label="角色名称" prop="title" />
        <el-table-column label="角色描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button size="small" type="primary" @click="assignPerm(row.id)">分配权限</el-button>
            <el-button>编辑</el-button>
            <el-button size="small" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog :visible="isShowPerm" @close="btnCancel">
      <el-checkbox-group v-model="checkedPerm">
        <el-tree :data="permList">
          <template v-slot="{data}">
            <el-checkbox :label="data.id">
              {{ data.title }}
            </el-checkbox>
          </template>
        </el-tree>
      </el-checkbox-group>
      <template #footer>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, getRoleDetail, updateRole } from '@/api/roles'
import { getPermissions } from '@/api/permissions'
export default {
  data() {
    return {
      roleList: [],
      permList: [],
      checkedPerm: [],
      roleId: '',
      isShowPerm: false
    }
  },
  created() {
    this.getRoles()
    this.getPermissions()
  },
  methods: {
    async getRoles() {
      this.roleList = await getRoles()
      console.log(this.roleList)
    },
    async getPermissions() {
      this.permList = await getPermissions()
    },
    async assignPerm(id) {
      this.isShowPerm = true
      const { permissions } = await getRoleDetail(id)
      this.roleId = id

      this.checkedPerm = permissions.map(p => p.id)
    },
    async btnOK() {
      await updateRole({
        id: this.roleId,
        permissions: this.checkedPerm
      })
      this.$message.success('修改成功')
      this.isShowPerm = false
    },
    btnCancel() {
      this.checkedPerm = []
      this.isShowPerm = false
    }
  }
}
</script>

<style>

</style>
